package com.example.mall_system.service.Impl;

import com.example.mall_system.common.Result;
import com.example.mall_system.entity.Product;
import com.example.mall_system.service.ProductService;
import com.example.mall_system.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Result getAllProducts(int page, int size, String keyword) {
        int start = (page - 1) * size;
        List<Product> products;
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            products = productMapper.findProductsByPageAndKeyword(start, size, keyword.trim());
        } else {
            products = productMapper.findProductsByPage(start, size);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("records", products);
        result.put("total", products.size()); // 简化处理，实际应该查询总数
        result.put("page", page);
        result.put("size", size);
        
        return Result.success(result);
    }

    @Override
    public Result<Product> getProductById(Long id) {
        Product product = productMapper.findProductById(id);
        if (product == null) {
            return Result.error(404, "商品不存在");
        }
        return Result.success(product);
    }

    @Override
    @Transactional
    public Result<Product> addProduct(Product product, Long userId, Integer role) {
        // 参数验证
        if (product.getName() == null || product.getName().trim().isEmpty()) {
            return Result.error(400, "商品名称不能为空");
        }
        if (product.getPrice() == null || product.getPrice() <= 0) {
            return Result.error(400, "商品价格必须大于0");
        }
        if (product.getCategory() == null || product.getCategory().trim().isEmpty()) {
            return Result.error(400, "商品分类不能为空");
        }
        if (product.getStock() == null || product.getStock() < 0) {
            return Result.error(400, "商品库存不能为负数");
        }

        // 设置卖家ID
        product.setSellerId(userId);
        
        // 设置默认值
        if (product.getStock() == null) {
            product.setStock(0);
        }
        if (product.getImage() == null) {
            product.setImage("/default-product.jpg");
        }
        
        Date now = new Date();
        product.setCreateTime(now);
        product.setUpdateTime(now);

        int rows = productMapper.insertProduct(product);
        if (rows > 0) {
            return Result.success(product);
        } else {
            return Result.error(500, "商品添加失败");
        }
    }

    @Override
    @Transactional
    public Result<Boolean> updateProduct(Product product, Long userId, Integer role) {
        // 验证商品是否存在
        Product existingProduct = productMapper.findProductById(product.getId());
        if (existingProduct == null) {
            return Result.error(404, "商品不存在");
        }

        // 权限验证：卖家只能更新自己的商品，管理员可以更新所有商品
        if (role == 1 && !existingProduct.getSellerId().equals(userId)) {
            return Result.error(403, "只能更新自己的商品");
        }

        // 参数验证
        if (product.getName() == null || product.getName().trim().isEmpty()) {
            return Result.error(400, "商品名称不能为空");
        }
        if (product.getPrice() == null || product.getPrice() <= 0) {
            return Result.error(400, "商品价格必须大于0");
        }
        if (product.getCategory() == null || product.getCategory().trim().isEmpty()) {
            return Result.error(400, "商品分类不能为空");
        }
        if (product.getStock() == null || product.getStock() < 0) {
            return Result.error(400, "商品库存不能为负数");
        }

        // 设置更新时间
        product.setUpdateTime(new Date());

        int rows = productMapper.updateProduct(product);
        if (rows > 0) {
            return Result.success(true);
        } else {
            return Result.error(500, "商品更新失败");
        }
    }

    @Override
    @Transactional
    public Result<Boolean> deleteProduct(Long id, Long userId, Integer role) {
        // 验证商品是否存在
        Product product = productMapper.findProductById(id);
        if (product == null) {
            return Result.error(404, "商品不存在");
        }

        // 权限验证：卖家只能删除自己的商品，管理员可以删除所有商品
        if (role == 1 && !product.getSellerId().equals(userId)) {
            return Result.error(403, "只能删除自己的商品");
        }

        int rows = productMapper.deleteProduct(id);
        if (rows > 0) {
            return Result.success(true);
        } else {
            return Result.error(500, "商品删除失败");
        }
    }

    @Override
    public Result<List<Product>> getProductsByCategory(String category) {
        List<Product> products = productMapper.findProductsByCategory(category);
        return Result.success(products);
    }

    @Override
    public Result<Boolean> checkAndUpdateStock(Long productId, Integer quantity) {
        Product product = productMapper.findProductById(productId);
        if (product == null) {
            return Result.error(404, "商品不存在");
        }
        if (product.getStock() < quantity) {
            return Result.error(400, "商品库存不足");
        }
        int rows = productMapper.updateStock(productId, quantity);
        if (rows > 0) {
            return Result.success(true);
        } else {
            return Result.error(500, "库存更新失败");
        }
    }

    @Override
    public Result getSellerProducts(Long sellerId) {
        List<Product> products = productMapper.findProductsBySellerId(sellerId);
        int total = productMapper.countProductsBySellerId(sellerId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("products", products);
        result.put("total", total);
        
        return Result.success(result);
    }

    @Override
    @Transactional
    public Result<Boolean> batchDeleteProducts(Long[] productIds, Long userId, Integer role) {
        if (productIds == null || productIds.length == 0) {
            return Result.error(400, "请选择要删除的商品");
        }

        // 验证权限：卖家只能删除自己的商品，管理员可以删除所有商品
        if (role == 1) {
            for (Long productId : productIds) {
                Product product = productMapper.findProductById(productId);
                if (product != null && !product.getSellerId().equals(userId)) {
                    return Result.error(403, "只能删除自己的商品");
                }
            }
        }

        int rows = productMapper.batchDeleteProducts(productIds);
        if (rows > 0) {
            return Result.success(true);
        } else {
            return Result.error(500, "批量删除失败");
        }
    }
}